<template>
  <div>
    <!-- 筛选条件 -->
    <div class="filter-container">
      <el-form :model="queryParams" :inline="true">
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 150px;">
            <el-option label="显示" value="1" />
            <el-option label="隐藏" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="管理员名称">
          <el-input
            v-model="queryParams.username"
            placeholder="请输入管理员名称"
            clearable
            maxlength="20"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="管理员昵称">
          <el-input
            v-model="queryParams.truename"
            placeholder="请输入管理员昵称"
            clearable
            maxlength="20"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input
            v-model="queryParams.phone"
            placeholder="请输入手机号"
            clearable
            maxlength="20"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="微信昵称">
          <el-input
            v-model="queryParams.weixin"
            placeholder="请输入微信昵称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="admin-management">
      <!-- 表格 -->
      <div class="header">
        <!-- <h2>超级管理员管理</h2> -->
        <el-button type="primary" v-permission="'admin:user/system_user:add'" @click="handleAdd">新增管理员</el-button>
      </div>
      <div class="table-container">
        <el-table
          v-loading="loading"
          :data="tableData"
          border
          style="width: 100%"
        >
          <el-table-column label="排序" width="80">
            <template #default="scope">
              <el-button
                link
                type="primary"
                @click="handleSort(scope.row)"
              >
                {{ scope.$index + 1 }}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="头像" width="80">
            <template #default="scope">
              <div class="avatar-container" @click="handleAvatarUpload(scope.row)">
                <el-avatar
                  :size="40"
                  :src="scope.row.avatar || defaultAvatar"
                  fit="cover"
                />
                <div v-if="uploadingAvatarId === scope.row.id" class="avatar-uploading">
                  <el-progress type="circle" :percentage="uploadProgress" :width="40" />
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="管理员名称" min-width="120" />
          <el-table-column prop="truename" label="管理员昵称" min-width="120" />
          <el-table-column prop="role" label="平台角色" width="120">
            <template #default="scope">
              <el-tag>{{ formatRole(scope.row.role) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="phone" label="手机号" min-width="120" />
          <el-table-column prop="weixin" label="微信昵称" min-width="120" />
          <el-table-column prop="mail" label="邮箱" min-width="150" />
          <el-table-column prop="sex" label="性别" width="80">
            <template #default="scope">
              {{ formatSex(scope.row.sex) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="80">
            <template #default="scope">
              <el-tag :type="scope.row.status === '1' ? 'success' : 'info'">
                {{ scope.row.status === '1' ? '显示' : '隐藏' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="160">
            <template #default="scope">
              {{ formatDate(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="scope">
              <el-button
                size="small"
                v-permission="'admin:user/system_user:edit'"
                @click="handleEdit(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                size="small"
                type="danger"
                v-permission="'admin:user/system_user:del'"
                @click="handleDelete(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>

      <!-- 新增/编辑对话框 -->
      <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="600px"
        :before-close="handleClose"
      >
        <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="120px"
        >
          <el-form-item label="头像" style="align-items: center;justify-content: center;">
            <div class="avatar-upload-container" @click="handleAvatarUpload(formData)">
              <el-avatar
                :size="80"
                :src="formData.avatar || defaultAvatar"
                fit="cover"
              />
              <div class="avatar-upload-mask">
                <el-icon><Camera /></el-icon>
              </div>
              <div v-if="uploadingAvatarId === 'form'" class="avatar-uploading-dialog">
                <el-progress type="circle" :percentage="uploadProgress" :width="60" />
              </div>
            </div>
          </el-form-item>
          <el-form-item label="管理员名称" prop="username">
            <el-input
              v-model="formData.username"
              placeholder="请输入管理员名称"
              maxlength="20"
              show-word-limit
            />
          </el-form-item>
          <el-form-item label="管理员昵称" prop="truename">
            <el-input
              v-model="formData.truename"
              placeholder="请输入管理员昵称"
              maxlength="20"
              show-word-limit
            />
          </el-form-item>
          <el-form-item label="管理员密码" prop="password">
            <el-input
              v-model="formData.password"
              type="password"
              placeholder="请输入管理员密码"
              maxlength="20"
              show-word-limit
              show-password
            />
          </el-form-item>
          <el-form-item label="平台角色" prop="role">
            <el-select v-model="formData.role" disabled>
              <el-option label="超级管理员" value="superAdmin" />
            </el-select>
          </el-form-item>
          <el-form-item label="用户状态" prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio label="1">显示</el-radio>
              <el-radio label="0">隐藏</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input
              v-model="formData.phone"
              placeholder="请输入手机号"
              maxlength="20"
              show-word-limit
            />
          </el-form-item>
          <el-form-item label="微信昵称">
            <el-input
              v-model="formData.weixin"
              placeholder="关联微信后显示"
              disabled
            />
          </el-form-item>
          <el-form-item label="邮箱" prop="mail">
            <el-input
              v-model="formData.mail"
              placeholder="请输入邮箱"
              maxlength="50"
              show-word-limit
            />
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="formData.sex">
              <el-radio label="1">男</el-radio>
              <el-radio label="2">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              v-model="formData.desc"
              type="textarea"
              :rows="3"
              placeholder="请输入备注"
              maxlength="150"
              show-word-limit
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="handleClose">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 头像上传 -->
      <input
        ref="avatarInputRef"
        type="file"
        accept="image/*"
        style="display: none"
        @change="handleAvatarChange"
      />
    </div>

  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Camera } from '@element-plus/icons-vue'
import { fileApi } from '@/api/file'
import { systemUserApi } from '@/api/user'
import { convertKeysToSnakeCase } from '@/utils/caseConverter'


// 类型定义
interface SystemUser {
  id?: number
  username: string
  password: string
  phone: string
  mail: string
  status: string
  desc: string
  truename: string
  avatar: string
  weixin: string
  sex: string
  role: string
  createTime?: string
  look:string
}

interface QueryParams {
  pageNum: number
  pageSize: number
  status: string
  username: string
  truename: string
  phone: string
  weixin: string
  role:string
}

// 响应式数据
const loading = ref(false)
const tableData = ref<SystemUser[]>([])
const total = ref(0)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref<FormInstance>()
const avatarInputRef = ref<HTMLInputElement>()
const currentRow = ref<SystemUser | null>(null)
const uploadingAvatarId = ref<string | number>('')
const uploadProgress = ref(0)

const defaultAvatar = '/default-avatar.png'

const queryParams = reactive<QueryParams>({
  pageNum: 1,
  pageSize: 10,
  status: '',
  username: '',
  truename: '',
  phone: '',
  weixin: '',
  role:'superAdmin'
})

const formData = reactive<SystemUser>({
  username: '',
  password: '',
  phone: '',
  mail: '',
  status: '1',
  desc: '',
  truename: '',
  avatar: '',
  weixin: '',
  sex: '1',
  role: 'superAdmin',
  look:''
})

// 表单验证规则
const formRules: FormRules = {
  username: [
    { required: true, message: '请输入管理员名称', trigger: 'blur' },
    { pattern: /^[A-Za-z0-9]+$/, message: '只能输入英文或数字', trigger: 'blur' },
    { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
  ],
  truename: [
    { required: true, message: '请输入管理员昵称', trigger: 'blur' },
    { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入管理员密码', trigger: 'blur' },
    { pattern: /^[A-Za-z0-9!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]+$/, message: '只能输入英文、数字或符号', trigger: 'blur' },
    { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择平台角色', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择用户状态', trigger: 'change' }
  ],
  phone: [
    { pattern: /^\d*$/, message: '只能输入数字', trigger: 'blur' },
    { max: 20, message: '长度不能超过20个字符', trigger: 'blur' }
  ],
  mail: [
    { pattern: /^[A-Za-z0-9@._-]+$/, message: '只能输入英文、数字或符号', trigger: 'blur' },
    { max: 50, message: '长度不能超过50个字符', trigger: 'blur' }
  ],
  sex: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ]
}

// 生命周期
onMounted(() => {
  getList()
})

// 方法
const getList = async () => {
  loading.value = true
  try {

    //API调用
    const res = await systemUserApi.getList(queryParams)
    tableData.value = res.data.list
    total.value = res.data.total
    
    // 模拟数据
    setTimeout(() => {
      loading.value = false
    }, 500)
  } catch (error) {
    loading.value = false
    ElMessage.error('获取数据失败')
  }
}

const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

const resetQuery = () => {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    status: '',
    username: '',
    truename: '',
    phone: '',
    weixin: '',
    role:'superAdmin'
  })
  getList()
}

const handleSizeChange = (val: number) => {
  queryParams.pageSize = val
  getList()
}

const handleCurrentChange = (val: number) => {
  queryParams.pageNum = val
  getList()
}

const handleAdd = () => {
  dialogTitle.value = '新增管理员'
  dialogVisible.value = true
  resetForm()
}

const handleEdit = (row: SystemUser) => {
  dialogTitle.value = '编辑管理员'
  dialogVisible.value = true
  nextTick(() => {
    row.password = row.look;
    Object.assign(formData, row)
  })
}

const handleDelete = async (row: SystemUser) => {
  try {
    await ElMessageBox.confirm(
      `确定删除管理员 "${row.truename}" 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用删除API
    const result = await systemUserApi.delete(row.id)
    if (result.code == 200) {
      ElMessage.success('删除成功')
      getList()
    } else {
      ElMessage.error('删除失败'+result.message)
      return false
    }
  } catch (error:any) {
    // 用户取消删除
    ElMessage.error('删除失败，请重试')
  }
}

const handleSort = (row: SystemUser) => {
  ElMessage.info(`排序功能开发中，当前操作管理员：${row.truename}`)
}

const handleAvatarUpload = (row: SystemUser) => {
  currentRow.value = row
  avatarInputRef.value?.click()
}

const handleAvatarChange = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (!file) return

  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    ElMessage.error('请上传图片文件')
    return
  }

  // 验证文件大小 (限制2MB)
  if (file.size > 2 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过2MB')
    return
  }

  try {
    // 设置上传状态
    if (currentRow.value?.id) {
      uploadingAvatarId.value = currentRow.value.id
    } else {
      uploadingAvatarId.value = 'form'
    }
    
    uploadProgress.value = 0

    // 调用上传API
    const result = await fileApi.upload(file, (progressEvent:any) => {
      if (progressEvent.total) {
        uploadProgress.value = Math.round(
          (progressEvent.loaded * 100) / progressEvent.total
        )
      }
    })

    console.log('上传结果:', result)

    // 上传成功，更新头像URL
    const avatarUrl = result.data.url
    
    if (currentRow.value) {
      if (currentRow.value.id) {
        // 编辑模式 - 更新表格中的头像
        const user = tableData.value.find(item => item.id === currentRow.value?.id)
        if (user) {
          user.avatar = avatarUrl
          formData.avatar = avatarUrl
        }
      } else {
        // 新增模式 - 更新表单中的头像
        formData.avatar = avatarUrl
      }
    }

    ElMessage.success('头像上传成功')
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('头像上传失败，请重试')
  } finally {
    // 重置上传状态
    uploadingAvatarId.value = ''
    uploadProgress.value = 0
    // 重置input，允许重复选择同一文件
    target.value = ''
  }
}

const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(formData, {
    username: '',
    password: '',
    phone: '',
    mail: '',
    status: '1',
    desc: '',
    truename: '',
    avatar: '',
    weixin: '',
    sex: '1',
    role: 'superAdmin'
  })
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    
    // 调用API保存数据
    if (formData.id) {
      // 编辑
      let json = convertKeysToSnakeCase(formData)
      const result = await systemUserApi.update(json)
      if (result.code == 200) {
        ElMessage.success('更新成功')
      } else {
        ElMessage.error('更新失败'+result.message)
        return false
      }
    } else {
      // 新增
      let json = convertKeysToSnakeCase(formData)
      const result = await systemUserApi.add(json)
      if (result.code == 200) {
        ElMessage.success('新增成功')
      } else {
        ElMessage.error('新增失败'+result.message)
        return false
      }
    }
    
    dialogVisible.value = false
    getList()
  } catch (error: any) {
    // 错误信息已经在子组件中显示
    console.error('表单提交错误:', error);
    if(error.code == 500||error.code == 400){
      ElMessage.error(error.message)
    }
  }

}

const formatRole = (role: string) => {
  const roleMap: Record<string, string> = {
    'superAdmin': '超级管理员',
    'admin': '管理员',
    'common': '普通用户',
    'tenant': '租户',
  }
  return roleMap[role] || role
}

const formatSex = (sex: string) => {
  const sexMap: Record<string, string> = {
    '1': '男',
    '2': '女'
  }
  return sexMap[sex] || sex
}

const formatDate = (dateString: string) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleString()
}
</script>

<style scoped>
.admin-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2px;
}

.filter-container {
  background: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 2px;
}

.table-container {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.avatar-container {
  display: flex;
  justify-content: center;
  cursor: pointer;
  position: relative;
}

.avatar-uploading {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 50%;
}

.avatar-upload-container {
  position: relative;
  width: 80px;
  height: 80px;
  cursor: pointer;
}

.avatar-upload-container:hover .avatar-upload-mask {
  display: flex;
}

.avatar-upload-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: none;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
}

.avatar-uploading-dialog {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 50%;
}
</style>